package server.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.FrmDictionDao;
import server.model.entity.FrmDiction;
import server.tool.operLog.OperLog;

import java.util.Dictionary;
import java.util.List;

@RestController
@RequestMapping("v1/api/swiper")
@CrossOrigin(origins = "*")
public class SwiperController {
    @Autowired
    private FrmDictionDao dictionarysDao;

    @GetMapping("/List")
    public RetResult List() {
        return RetResponse.makeOKRsp(dictionarysDao.findByTypeOrderByKeyst("SWIPER"));
    }


    @GetMapping("/List/{type}")
    public RetResult zp(@PathVariable String type) {
        return RetResponse.makeOKRsp(dictionarysDao.findByTypeOrderByKeyst(type));
    }
    @PostMapping("/Save")
    public RetResult Save(@RequestBody FrmDiction diction) {
        try {
            if (StringUtils.isEmpty(diction.getId())) {
                if (diction.getType().equals("ZP")) {
                    List<FrmDiction> dic = dictionarysDao.findByTypeOrderByKeyst("ZP");
                    if (dic.stream().mapToDouble(item -> Double.parseDouble(item.getVal4())).sum()
                            + Double.parseDouble(diction.getVal4()) > 1) {
                        return RetResponse.makeErrRsp("概率不能大于1");
                    }
                }
                dictionarysDao.save(diction);
            } else {
                FrmDiction entity = dictionarysDao.findById(diction.getId()).get();
                entity.setVal(diction.getVal());
                dictionarysDao.save(entity);
            }
        } catch (Exception e) {
            return RetResponse.makeErrRsp("排序已存在！");
        }
        return RetResponse.makeOKRsp();
    }

    @OperLog("轮播删除")
    @DeleteMapping("/{id}")
    public RetResult Deleted(@PathVariable String id) {
        dictionarysDao.deleteById(id);
        return RetResponse.makeOKRsp();
    }
}
